本篇同步發布於Blog:[解題] LeetCode - 7 Reverse Integer
LeetCode
7 - Reverse Integer
https://leetcode.com/problems/reverse-integer/
給一個32位元的整數x,求他的位數反轉。但如果反轉後的位數會overflow,則回傳0。
比如x = 123,答案為321;x = -123,答案為-321;x = 1234567899,答案為0。
建立一個long的變數ans,不斷地將x的第1位數轉成ans新的進位數。最終再用Math函式庫的abs檢查是否ans超出32位元整數的最大值,超過就回傳0,否則回傳轉型32位元的ans。
難度為Easy
#include <iostream>
#include <cmath>
#include <climits>
using namespace std;
class Solution {
public:
int reverse(int x) {
long ans = 0;
while(x != 0){
ans = ans * 10 + (x % 10);
x /= 10;
}
return fabs(ans) > INT_MAX ? 0 : ans;
}
};
int main() {
Solution sol;
cout << sol.reverse(123) << endl;
cout << sol.reverse(-123) << endl;
cout << sol.reverse(1234567899) << endl;
return 0;
}
using System;
namespace LeetCode7
{
public class Solution {
public int Reverse(int x) {
long ans = 0;
while(x != 0){
ans = ans * 10 + (x % 10);
x /= 10;
}
return Math.Abs(ans) > Int32.MaxValue ? 0 : (int)ans;
}
}
public class Program
{
public static void Main()
{
Solution sol = new Solution();
Console.WriteLine(sol.Reverse(123));
Console.WriteLine(sol.Reverse(-123));
Console.WriteLine(sol.Reverse(1234567899));
Console.Read();
}
}
}
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%2B%2B/1-99/7.cpp
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%23/1-99/7.cs